<template>
  <view class="publish-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left" @click="handleCancel">
          <u-icon name="close" color="white" size="20"></u-icon>
          <text class="nav-text">取消</text>
        </view>
        <text class="navbar-title">发布动态</text>
        <view class="navbar-right" @click="handlePublish">
          <text class="publish-btn" :class="{ disabled: !canPublish }">发布</text>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view class="main-content" scroll-y>
      <!-- 圈子选择 -->
      <view class="circle-selector modern-card">
        <view class="selector-header">
          <u-icon name="grid" color="#667eea" size="18"></u-icon>
          <text class="selector-title">选择圈子</text>
        </view>
        <view class="selected-circle" @click="showCircleModal = true">
          <view class="circle-info" v-if="selectedCircle">
            <image :src="selectedCircle.cover_image || '/static/images/default-avatar.png'" class="circle-avatar" mode="aspectFill"></image>
            <text class="circle-name">{{ selectedCircle.cate_name || '未命名圈子' }}</text>
          </view>
          <view class="placeholder" v-else>
            <text class="placeholder-text">请选择发布圈子</text>
          </view>
          <u-icon name="arrow-right" color="#999" size="16"></u-icon>
        </view>
      </view>
      <view class="content-editor modern-card">
        <!-- 文本输入 -->
        <view class="text-input-section">
          <textarea
              v-model="postForm.content"
              placeholder="分享你的想法..."
              class="content-textarea"
              :maxlength="500"
              auto-height
              @input="handleContentInput"
          ></textarea>
          <view class="char-count">
            <text class="count-text">{{ postForm.content.length }}/500</text>
          </view>
        </view>

        <!-- 图片上传区域 -->
        <view class="image-upload-section">
          <view class="upload-grid">
            <!-- 已上传的图片 -->
            <view
                class="image-item"
                v-for="(image, index) in postForm.images"
                :key="index"
            >
              <image :src="image.url" class="uploaded-image" mode="aspectFill"></image>
              <view class="image-actions">
                <view class="action-btn" @click="previewImage(getImageUrls(), index)">
                  <u-icon name="eye" color="white" size="16"></u-icon>
                </view>
                <view class="action-btn delete" @click="removeImage(index)">
                  <u-icon name="close" color="white" size="16"></u-icon>
                </view>
              </view>
            </view>

            <!-- 上传按钮 -->
            <view
                class="upload-btn"
                v-if="postForm.images.length < 9"
                @click="chooseImage"
            >
              <u-icon name="plus" color="#999" size="30"></u-icon>
              <text class="upload-text">添加图片</text>
            </view>
          </view>
          <view class="upload-tip">
            <text class="tip-text">最多可上传9张图片</text>
          </view>
        </view>

        <!-- 话题标签 -->
        <view class="topic-section">
          <view class="section-header">
            <u-icon name="tag" color="#667eea" size="18"></u-icon>
            <text class="section-title">添加话题</text>
          </view>
          <view class="topic-input-container">
            <input
                v-model="topicInput"
                placeholder="输入话题名称"
                class="topic-input"
                @confirm="addTopic"
            />
            <u-button
                size="mini"
                type="primary"
                :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
                @click="addTopic"
            >
              添加
            </u-button>
          </view>
          <view class="topic-list" v-if="postForm.topics.length > 0">
            <view
                class="topic-tag"
                v-for="(topic, index) in postForm.topics"
                :key="index"
            >
              <text class="topic-text">#{{ topic }}</text>
              <u-icon name="close" color="#667eea" size="14" @click="removeTopic(index)"></u-icon>
            </view>
          </view>
        </view>

        <!-- 位置信息 -->
        <view class="location-section">
          <view class="section-header">
            <u-icon name="map-pin" color="#667eea" size="18"></u-icon>
            <text class="section-title">添加位置</text>
          </view>
          <view class="location-selector" @click="chooseLocation">
            <view class="location-info" v-if="postForm.location">
              <text class="location-name">{{ postForm.location.name }}</text>
              <text class="location-address">{{ postForm.location.address }}</text>
            </view>
            <view class="placeholder" v-else>
              <text class="placeholder-text">选择位置</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="16"></u-icon>
          </view>
        </view>
      </view>

      <!-- 发布设置 -->
      <view class="publish-settings modern-card">
        <view class="setting-item">
          <view class="setting-info">
            <u-icon name="eye" color="#667eea" size="18"></u-icon>
            <text class="setting-title">谁可以看</text>
          </view>
          <view class="setting-value" @click="showPrivacyModal = true">
            <text class="value-text">{{ getPrivacyLabel() }}</text>
            <u-icon name="arrow-right" color="#999" size="16"></u-icon>
          </view>
        </view>

        <view class="setting-item">
          <view class="setting-info">
            <u-icon name="chat" color="#667eea" size="18"></u-icon>
            <text class="setting-title">允许评论</text>
          </view>
          <u-switch
              v-model="postForm.allowComment"
              active-color="#667eea"
          ></u-switch>
        </view>
      </view>

      <!-- 底部占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>

    <!-- 圈子选择弹窗 -->
    <u-popup v-model="showCircleModal" mode="bottom" border-radius="20">
      <view class="circle-modal">
        <view class="modal-header">
          <text class="modal-title">选择圈子</text>
          <u-icon name="close" color="#999" size="20" @click="showCircleModal = false"></u-icon>
        </view>

        <scroll-view class="circle-list" scroll-y>
          <view
              class="circle-option"
              :class="{ selected: selectedCircle && selectedCircle.id === circle.id }"
              v-for="circle in circleList"
              :key="circle.id"
              @click="selectCircle(circle)"
          >
            <image :src="circle.cover_image" class="option-avatar" mode="aspectFill"></image>
            <view class="option-info">
              <text class="option-name">{{ circle.cate_name }}</text>
              <text class="option-desc">{{ circle.member_count }}成员</text>
            </view>
            <u-icon
              v-if="selectedCircle && selectedCircle.id === circle.id"
              name="checkmark-circle-fill"
              color="#667eea"
              size="20"
            ></u-icon>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <!-- 隐私设置弹窗 -->
    <u-popup v-model="showPrivacyModal" mode="bottom" border-radius="20">
      <view class="privacy-modal">
        <view class="modal-header">
          <text class="modal-title">隐私设置</text>
          <u-icon name="close" color="#999" size="20" @click="showPrivacyModal = false"></u-icon>
        </view>

        <view class="privacy-options">
          <view
              class="privacy-option"
              :class="{ selected: postForm.privacy === option.value }"
              v-for="option in privacyOptions"
              :key="option.value"
              @click="selectPrivacy(option.value)"
          >
            <view class="option-content">
              <u-icon :name="option.icon" color="#667eea" size="20"></u-icon>
              <view class="option-text">
                <text class="option-title">{{ option.label }}</text>
                <text class="option-desc">{{ option.desc }}</text>
              </view>
            </view>
            <u-icon
                v-if="postForm.privacy === option.value"
                name="checkmark-circle-fill"
                color="#667eea"
                size="20"
            ></u-icon>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 位置选择弹窗 -->
    <u-popup v-model="showLocationModal" mode="bottom" border-radius="20">
      <view class="location-modal">
        <view class="modal-header">
          <text class="modal-title">选择位置</text>
          <u-icon name="close" color="#999" size="20" @click="showLocationModal = false"></u-icon>
        </view>

        <view class="location-search">
          <input
              v-model="locationSearch"
              placeholder="搜索位置"
              class="search-input"
              @input="searchLocation"
          />
        </view>

        <scroll-view class="location-list" scroll-y>
          <view
              class="location-option"
              v-for="location in locationList"
              :key="location.id"
              @click="selectLocation(location)"
          >
            <u-icon name="map-pin" color="#667eea" size="18"></u-icon>
            <view class="location-details">
              <text class="location-name">{{ location.name }}</text>
              <text class="location-address">{{ location.address }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <!-- Toast提示 -->
    

    <!-- 加载遮罩 -->
    <u-loading-page :loading="publishing" loading-text="发布中..."></u-loading-page>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      publishing: false,
      showCircleModal: false,
      showPrivacyModal: false,
      showLocationModal: false,
      topicInput: '',
      locationSearch: '',

      // 发布表单数据
      postForm: {
        content: '',
        images: [],
        topics: [],
        location: null,
        privacy: 'public',
        allowComment: true,
        circleId: ''
      },

      // 选中的圈子
      selectedCircle: null,

      // 圈子列表
      circleList: [],

      // 隐私选项
      privacyOptions: [
        {
          value: 'public',
          label: '公开',
          desc: '所有人都可以看到',
          icon: 'globe'
        },
        {
          value: 'circle',
          label: '圈子成员',
          desc: '只有圈子成员可以看到',
          icon: 'account-fill'
        },
        {
          value: 'friends',
          label: '好友',
          desc: '只有关注的人可以看到',
          icon: 'heart-fill'
        }
      ],

      // 位置列表
      locationList: []
    }
  },

  computed: {
    canPublish() {
      return this.postForm.content.trim().length > 0 && this.selectedCircle
    }
  },

  onLoad(options) {
    this.initPage()

    // 如果从圈子页面跳转过来，预选圈子
    if (options.circleId) {
      this.preSelectCircle(options.circleId)
    }
  },

  methods: {
    // 初始化页面
    async initPage() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0

      await this.loadCircleList()
      this.loadLocationList()
    },

    // 加载圈子列表
    async loadCircleList() {
      try {
        // 模拟数据
        this.circleList = [
          {
            id: 1,
            cate_name: '校园生活',
            cover_image: '/static/images/circle/circle1.png',
            member_count: 1234
          },
          {
            id: 2,
            cate_name: '摄影爱好',
            cover_image: '/static/images/circle/circle2.png',
            member_count: 856
          },
          {
            id: 3,
            cate_name: '美食分享',
            cover_image: '/static/images/circle/circle3.png',
            member_count: 2341
          }
        ]
      } catch (error) {
        console.error('加载圈子列表失败:', error)
      }
    },

    // 预选圈子
    preSelectCircle(circleId) {
      const circle = this.circleList.find(item => item.id == circleId)
      if (circle) {
        this.selectedCircle = circle
        this.postForm.circleId = circleId
      }
    },

    // 加载位置列表
    loadLocationList() {
      // 模拟位置数据
      this.locationList = [
        {
          id: 1,
          name: '北京大学',
          address: '北京市海淀区颐和园路5号'
        },
        {
          id: 2,
          name: '清华大学',
          address: '北京市海淀区清华园1号'
        },
        {
          id: 3,
          name: '中关村',
          address: '北京市海淀区中关村大街'
        }
      ]
    },

    // 内容输入处理
    handleContentInput(e) {
      this.postForm.content = e.detail.value
    },

    // 选择图片
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 9 - this.postForm.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })

        // 上传图片
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          await this.uploadImage(res.tempFilePaths[i])
        }
      } catch (error) {
        console.error('选择图片失败:', error)
      }
    },

    // 上传图片
    async uploadImage(filePath) {
      try {
        // 这里应该调用实际的上传API
        // const uploadRes = await this.$api.uploadImage(filePath)

        // 模拟上传成功
        this.postForm.images.push({
          url: filePath,
          id: Date.now()
        })

        this.showToast('图片上传成功', 'success')
      } catch (error) {
        console.error('上传图片失败:', error)
        this.showToast('图片上传失败', 'error')
      }
    },

    // 移除图片
    removeImage(index) {
      this.postForm.images.splice(index, 1)
    },

    // 预览图片
    previewImage(urls, current) {
      uni.previewImage({
        urls,
        current
      })
    },

    // 添加话题
    addTopic() {
      const topic = this.topicInput.trim()
      if (!topic) {
        this.showToast('请输入话题名称', 'error')
        return
      }

      if (this.postForm.topics.includes(topic)) {
        this.showToast('话题已存在', 'error')
        return
      }

      if (this.postForm.topics.length >= 5) {
        this.showToast('最多添加5个话题', 'error')
        return
      }

      this.postForm.topics.push(topic)
      this.topicInput = ''
    },

    // 移除话题
    removeTopic(index) {
      this.postForm.topics.splice(index, 1)
    },

    // 选择位置
    chooseLocation() {
      this.showLocationModal = true
    },

    // 搜索位置
    searchLocation() {
      // 这里应该调用位置搜索API
      console.log('搜索位置:', this.locationSearch)
    },

    // 选择圈子
    selectCircle(circle) {
      this.selectedCircle = circle
      this.postForm.circleId = circle.id
      this.showCircleModal = false
    },

    // 选择隐私设置
    selectPrivacy(privacy) {
      this.postForm.privacy = privacy
      this.showPrivacyModal = false
    },

    // 选择位置
    selectLocation(location) {
      this.postForm.location = location
      this.showLocationModal = false
    },

    // 取消发布
    async handleCancel() {
      if (this.postForm.content.trim() || this.postForm.images.length > 0) {
        const res = await uni.showModal({
          title: '确认取消',
          content: '取消后内容将不会保存，确定要取消吗？'
        })

        if (!res.confirm) return
      }

      uni.navigateBack()
    },

    // 发布帖子
    async handlePublish() {
      if (!this.canPublish) {
        this.showToast('请完善发布内容', 'error')
        return
      }

      this.publishing = true

      try {
        // 构建发布数据
        const publishData = {
          content: this.postForm.content.trim(),
          images: this.getImageUrls(),
          topics: this.postForm.topics,
          location: this.postForm.location,
          privacy: this.postForm.privacy,
          allowComment: this.postForm.allowComment,
          circleId: this.postForm.circleId
        }

        // 这里应该调用发布API
        // const res = await this.$api.publishPost(publishData)

        // 模拟发布成功
        await new Promise(resolve => setTimeout(resolve, 2000))

        this.showToast('发布成功', 'success')

        // 跳转到圈子详情页或首页
        setTimeout(() => {
          if (this.selectedCircle) {
            this.$tab.redirectTo('/pages/circles/detail?id=' + this.selectedCircle.id)
          } else {
            this.$tab.switchTab('/pages/index')
          }
        }, 1500)

      } catch (error) {
        console.error('发布失败:', error)
        this.showToast('发布失败，请重试', 'error')
      } finally {
        this.publishing = false
      }
    },

    // 获取图片URL数组
    getImageUrls() {
      const urls = []
      for (let i = 0; i < this.postForm.images.length; i++) {
        urls.push(this.postForm.images[i].url)
      }
      return urls
    },

    // 获取隐私设置标签
    getPrivacyLabel() {
      const option = this.privacyOptions.find(item => item.value === this.postForm.privacy)
      return option ? option.label : '公开'
    },

    // 显示提示
    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.modern-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.publish-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;

    .navbar-left {
      display: flex;
      align-items: center;
      gap: 5px;

      .nav-text {
        font-size: 16px;
        color: white;
      }
    }

    .navbar-title {
      font-size: 18px;
      font-weight: 600;
      color: white;
    }

    .navbar-right {
      .publish-btn {
        font-size: 16px;
        color: white;
        font-weight: 600;

        &.disabled {
          opacity: 0.5;
        }
      }
    }
  }
}

.main-content {
  padding-top: 88px;
  height: calc(100vh - 88px);
  padding: 88px 15px 0;
}

.circle-selector {
  margin-bottom: 15px;
  padding: 15px;

  .selector-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;

    .selector-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
  }

  .selected-circle {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .circle-info {
      display: flex;
      align-items: center;
      gap: 10px;

      .circle-avatar {
        width: 30px;
        height: 30px;
        border-radius: 15px;
      }

      .circle-name {
        font-size: 14px;
        color: #333;
      }
    }

    .placeholder {
      .placeholder-text {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.content-editor {
  margin-bottom: 15px;
  padding: 15px;

  .text-input-section {
    position: relative;
    margin-bottom: 20px;

    .content-textarea {
      width: 100%;
      min-height: 120px;
      font-size: 16px;
      color: #333;
      line-height: 1.5;
      background: transparent;
      border: none;
      outline: none;
      resize: none;
    }

    .char-count {
      position: absolute;
      bottom: 5px;
      right: 5px;

      .count-text {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .image-upload-section {
    margin-bottom: 20px;

    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 10px;

      .image-item {
        position: relative;
        width: calc(33.33% - 7px);
        height: 100px;

        .uploaded-image {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }

        .image-actions {
          position: absolute;
          top: 5px;
          right: 5px;
          display: flex;
          gap: 5px;

          .action-btn {
            width: 24px;
            height: 24px;
            border-radius: 12px;
            background: rgba(0, 0, 0, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;

            &.delete {
              background: rgba(255, 71, 87, 0.8);
            }
          }
        }
      }

      .upload-btn {
        width: calc(33.33% - 7px);
        height: 100px;
        border: 2px dashed #ddd;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 5px;

        .upload-text {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .upload-tip {
      .tip-text {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .topic-section {
    margin-bottom: 20px;

    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;

      .section-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
    }

    .topic-input-container {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 10px;

      .topic-input {
        flex: 1;
        height: 36px;
        padding: 0 12px;
        border: 1px solid #e0e0e0;
        border-radius: 18px;
        font-size: 14px;
        background: #f8f9fa;
      }
    }

    .topic-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .topic-tag {
        display: flex;
        align-items: center;
        gap: 5px;
        padding: 5px 10px;
        background: rgba(102, 126, 234, 0.1);
        border-radius: 15px;

        .topic-text {
          font-size: 12px;
          color: #667eea;
        }
      }
    }
  }

  .location-section {
    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;

      .section-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
    }

    .location-selector {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .location-info {
        .location-name {
          font-size: 14px;
          color: #333;
          display: block;
          margin-bottom: 2px;
        }

        .location-address {
          font-size: 12px;
          color: #999;
        }
      }

      .placeholder {
        .placeholder-text {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
}

.publish-settings {
  margin-bottom: 15px;
  padding: 15px;

  .setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;

    &:not(:last-child) {
      border-bottom: 1px solid #f0f0f0;
    }

    .setting-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .setting-title {
        font-size: 14px;
        color: #333;
      }
    }

    .setting-value {
      display: flex;
      align-items: center;
      gap: 5px;

      .value-text {
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.bottom-placeholder {
  height: 50px;
}

// 弹窗样式
.circle-modal, .privacy-modal, .location-modal {
  padding: 20px;
  max-height: 60vh;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .modal-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }
}

.circle-list {
  max-height: 40vh;

  .circle-option {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    &.selected {
      background: rgba(102, 126, 234, 0.05);
    }

    .option-avatar {
      width: 40px;
      height: 40px;
      border-radius: 20px;
      margin-right: 12px;
    }

    .option-info {
      flex: 1;

      .option-name {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .option-desc {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.privacy-options {
  .privacy-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    &.selected {
      background: rgba(102, 126, 234, 0.05);
    }

    .option-content {
      display: flex;
      align-items: center;
      gap: 12px;

      .option-text {
        .option-title {
          font-size: 14px;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 4px;
        }

        .option-desc {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.location-search {
  margin-bottom: 15px;

  .search-input {
    width: 100%;
    height: 40px;
    padding: 0 15px;
    border: 1px solid #e0e0e0;
    border-radius: 20px;
    font-size: 14px;
    background: #f8f9fa;
  }
}

.location-list {
  max-height: 40vh;

  .location-option {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    .location-details {
      .location-name {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .location-address {
        font-size: 12px;
        color: #999;
      }
    }
  }
}
</style>
